package com.zxy.supplier_system.server.entity

import jakarta.persistence.*
import org.hibernate.annotations.DynamicInsert
import org.hibernate.annotations.DynamicUpdate
import java.io.Serializable

@Entity
@DynamicUpdate
@DynamicInsert
@Table(
    uniqueConstraints = [
        UniqueConstraint(
            name = "market_order_item_market_order_id_goods_id_sub_goods_id_uindex",
            columnNames = ["market_order_id", "goods_id","sub_goods_id"]
        )
    ]
)
class MarketOrderItem:Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int?=null

    @ManyToOne(optional = false,cascade = [CascadeType.MERGE])
    @JoinColumn
    lateinit var goods: Goods

    @ManyToOne(optional = true, cascade = [CascadeType.MERGE])
    @JoinColumn(nullable = true)
    var subGoods: SubGoods? = null

    @Column(nullable = false)
    var amount: Int = 0

    @ManyToOne(optional = false)
    @JoinColumn(nullable = false)
    lateinit var marketOrder: MarketOrder

    var sequence: Int = 0

    @ManyToOne(cascade = [CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH])
    @JoinColumn
    var unit: GoodsUnit? = null

    @get:Transient
    val amountWithUnit: Int
        get() = if (unit == null) amount else amount * unit!!.basicMultiple

    var note:String? = null

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is MarketOrderItem) return false

        if (goods != other.goods) return false
        if (marketOrder != other.marketOrder) return false

        return true
    }

    override fun hashCode(): Int {
        var result = goods.hashCode()
        result = 31 * result + marketOrder.hashCode()
        return result
    }

    override fun toString(): String {
        return "MarketOrderItem(goods=$goods, amount=$amount, marketOrder=$marketOrder, sequence=$sequence, unit=$unit)"
    }


}

val List<MarketOrderItem>.nextSequence: Int
    get() = this.maxOfOrNull {
        it.sequence
    }?.plus(1) ?: 0
